<?php
/**
 * Description of PetFacade
 *
 * @author Alexey
 */
class PetFacade {
    //put your code here

    public static function savePet(Pet $pet)
    {
        return $pet->save();
    }

    public static function deletePet(Pet $pet)
    {
        $pet->delete();
    }

    public static function loadModel($id)
    {
        return Pet::model()->findByPk((int)$id);
    }
    
    public static function getPetsByUserId($userId)
    {        
        return Pet::model()->findAll("user_id=:userId", array(':userId' => $userId));
    }
    
    public static function getLatestPetsByUser($userId)
    {
        return Pet::model()->latest()->findAll("user_id=:userId", array(':userId' => $userId));
    }
    
    public static function getPetsCountByUserId($userId)
    {
        return Pet::model()->count('user_id=:userId', array(':userId' => $userId));
    }
    
    public static function getPetAvatarUrl(Pet $model)
    {
        if ($model->avatar)
        {
            return '/uploads/pets/' . $model->pet_id . '/avatar/' . $model->avatar;
        }
        else
        {
            return '/images/no-photo.gif';
        }
    }
    
    public static function getPetAvatarPath(Pet $model)
    {
        return Yii::getPathOfAlias('webroot') . '/uploads/pets/' . $model->pet_id . '/avatar/';
    }
    
    public static function getPetUploadsDir(Pet $model)
    {
        return Yii::getPathOfAlias('webroot') . '/uploads/pets/' . $model->pet_id;
    }
    
    public static function getPetsDir(Pet $model)
    {
        return Yii::getPathOfAlias('webroot') . '/uploads/pets/';
    }

    public static function savePetAvatar($uploadImage, Pet $pet)
    {
        $pet->avatar_id = $uploadImage->image_id;
        PetFacade::savePet($pet);
    }

    public static function deletePetAvatar($pet)
    {
        $imageId = $pet->avatar_id;
        $pet->avatar_id = null;
        $pet->save();
        UploadImageFacade::unsetImage($imageId);
    }

    public static function getRandPets($count)
    {
        $criteria = new CDbCriteria();
        $criteria->order = "rand()";
        $criteria->limit = $count;
        $pet = Pet::model()->findAll($criteria);
        return $pet;
    }

    public static function isAuthor($pet)
    {
        return ($pet->user_id == Yii::app()->controller->getUserIdFromSession());
    }

    public static function getDataProviderForSearch($nickname, $type, $race)
    {
        $criteria = new CDbCriteria();
        if (!empty($nickname ))
            $criteria->addSearchCondition( 'nickname', $nickname, true, 'OR' );
        if (!empty($type ))
            $criteria->addSearchCondition( 'type', $type, true, 'OR' );
        if (!empty($race ))
            $criteria->addSearchCondition( 'race', $race, true, 'OR' );

        $dataProvider = new CActiveDataProvider( 'Pet', array( 'criteria' => $criteria, ) );
        return $dataProvider;

    }

}
?>
